package per.wsj.commonlib.permission;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class PermissionFragment extends Fragment {

    private String[] mPermission;
    private PermissionListener mPermissionListener;

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPermissionListener = null;
    }

    private ActivityResultLauncher<String[]> launcher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
        List<String> permissionDeny = new ArrayList<>();
        Set<String> keys = result.keySet();
        for (String key : keys) {
            if (result.get(key) != null && !result.get(key)) {
                permissionDeny.add(key);
            }
        }
        if (permissionDeny.isEmpty()) {
            permissionsGranted();
        } else {
            permissionsDenied(permissionDeny);
        }
    });

    public void request(String[] permissions, PermissionListener permissionListener) {
        this.mPermission = permissions;
        this.mPermissionListener = permissionListener;
        if (PermissionUtil.hasPermission(requireContext(), permissions)) {
            permissionsGranted();
        } else {
            launcher.launch(permissions);
        }
    }

    /*@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != PERMISSIONS_REQUEST_CODE) return;

        if (PermissionUtil.isGranted(grantResults)
                && PermissionUtil.hasPermission(getActivity(), permissions)) {
            permissionsGranted();
        } else { //不需要提示用户
            permissionsDenied();
        }
    }*/

    private void permissionsDenied(List<String> permissionDeny) {
        if (mPermissionListener != null) {
            mPermissionListener.permissionDenied(permissionDeny.toArray(new String[0]));
        }
    }

    // 全部权限均已获取
    private void permissionsGranted() {
        if (mPermissionListener != null) {
            mPermissionListener.permissionGranted(mPermission);
        }
    }
}
